package cn.huaqingcheng.tool.core;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.ValidationException;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.executable.ExecutableValidator;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 验证工具
 */
@SuppressWarnings("unused")
public final class ValidationTool {

    private static final Validator VALIDATOR;

    private static final ExecutableValidator EXECUTABLE_VALIDATOR;

    static {
        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
            VALIDATOR = factory.getValidator();
            EXECUTABLE_VALIDATOR = VALIDATOR.forExecutables();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 验证断言
     *
     * @param o 待验证对象
     * @throws ValidationException 如果验证不通过 抛出异常
     */
    public static <T> void validateAssert(T o) {
        Set<ConstraintViolation<T>> violationSet = VALIDATOR.validate(o);
        if (violationSet.isEmpty()) {
            return;
        }
        String msg = violationSet.stream()
            .map(i -> String.format("%s %s", i.getPropertyPath(), i.getMessage()))
            .collect(Collectors.joining(";"));
        throw new ValidationException(msg);
    }

}
